package Cowquisition;

import java.util.Random;

/**
 * Cow class
 *
 * Defines a Thread that controls the AI (term AI used rather liberally) cows.
 * @author Ryan Novak
 */
public class Cow implements Runnable
{
  /** The x coordinate of the Cow. */
  private int x;
  /** The y coordinate of the Cow. */
  private int y;
  /** The type of the Cow (determines which tile color to use). */
  private int type;
  /** The type of the Cow (determines which tile color to use). */
  private Random rand;
  
  /**
   * Constructor for the Cow class
   *
   * @param typeIn The type (color) of the Cow
   */
  public Cow(int typeIn)
  {
    rand = new Random();
    x = rand.nextInt(Cowquisition.XSIZE / 4) + ((Cowquisition.XSIZE / 2) - Cowquisition.XSIZE / 8);
    y = rand.nextInt(Cowquisition.YSIZE / 4) + ((Cowquisition.YSIZE / 2) - Cowquisition.YSIZE / 8);
    type = typeIn;
  }

  /**
   * moove method
   *
   * Moves the cow in a random direction.
   */
  private synchronized void moove()
  {
    switch(rand.nextInt(4))
    {
      case 0:
        if(Cowquisition.map.canWalk(x + 1, y))
        {
          x++;
          Cowquisition.map.setCow(x, y, type);
          Cowquisition.map.desetCow(x - 1, y);
          Cowquisition._.drawCow(x, y);
        }
        break;
      case 1:
        if(Cowquisition.map.canWalk(x - 1, y))
        {
          x--;
          Cowquisition.map.setCow(x, y, type);
          Cowquisition.map.desetCow(x + 1, y);
          Cowquisition._.drawCow(x, y);
        }
        break;
      case 2:
        if(Cowquisition.map.canWalk(x, y + 1))
        {
          y++;
          Cowquisition.map.setCow(x, y, type);
          Cowquisition.map.desetCow(x, y - 1);
          Cowquisition._.drawCow(x, y);
        }
        break;
      case 3:
        if(Cowquisition.map.canWalk(x, y - 1))
        {
          y--;
          Cowquisition.map.setCow(x, y, type);
          Cowquisition.map.desetCow(x, y + 1);
          Cowquisition._.drawCow(x, y);
        }
        break;
    }
  }
  
  /**
   * run method
   *
   * The thread task; sleeps then moves.
   */
  public void run()
  {
    while(true)
    {
      try
      {
        Thread.sleep((rand.nextInt(5) + 1) * 1000);
      }
      catch(InterruptedException i)
      {
        System.out.print("a thread was interrupted");
      }
      moove();
    }
  }
}
